package xyz.fivefaith.tool.mybatis.injector.method;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import xyz.fivefaith.tool.mybatis.injector.AbstractPredicateMethod;

import java.util.function.Predicate;

/**
 * 根据 whereEntity 条件，更新记录(但是不包含逻辑删除)根据 whereEntity 条件，更新记录(但是不包含逻辑删除)
 *
 * @author zhaoanchi
 * @version 1.0
 * @since 2023-09-18 16:02
 */
public class AlwaysUpdate extends AbstractPredicateMethod<TableFieldInfo> {

    /**
     * @param name 方法名
     * @param predicate 筛选条件
     * @since 3.5.0
     */
    public AlwaysUpdate(String name, Predicate<TableFieldInfo> predicate) {
        super(name);
        this.predicate = predicate;
    }

    public AlwaysUpdate() {
        super("alwaysUpdate");
    }

    /**
     * @param predicate 筛选条件
     */
    public AlwaysUpdate(Predicate<TableFieldInfo> predicate) {
        super("alwaysUpdate");
        this.predicate = predicate;
    }

    @Override
    protected Predicate<TableFieldInfo> getPredicate() {
        Predicate<TableFieldInfo> noLogic = t -> !t.isLogicDelete();
        if (predicate != null) {
            return predicate;
        }
        return noLogic;
    }

    @Override
    public MappedStatement injectMappedStatement(
            Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlMethod sqlMethod = SqlMethod.UPDATE;
        String sql =
                String.format(
                        sqlMethod.getSql(),
                        tableInfo.getTableName(),
                        sqlSet(false, true, tableInfo, true, ENTITY, ENTITY_DOT),
                        sqlWhereEntityWrapper(false, true, tableInfo),
                        sqlComment());
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
    }
}
